//
// Created by yanhai on 2019/11/15.
//

#pragma once

#include <list>
#include <memory>
#include <json/json.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <sstream>

#include "base_request.hpp"
#include "utility/string.hpp"
#include "utility/urldecode.hpp"
#include "formparser.hpp"

class Request: public BaseRequest {
public:
    explicit Request(struct evhttp_request *request);

    void parse();

    const Json::Value &json() const
    {
        return _json;
    }

private:
    void _parse_json();

private:
    Json::Value _json;
};

// detail

inline Request::Request(evhttp_request *request) : BaseRequest(request)
{

}

inline void Request::_parse_json()
{
    JSONCPP_STRING err;
    Json::CharReaderBuilder builder;
    const std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
    if (!reader->parse(_body.c_str(), _body.c_str() + _body.length(), &_json, &err)) {
        throw RequestParseBodyException("request body not is a json std::string.");
    }
}

inline void Request::parse()
{
    _get_stream();
    if (content_type == "application/json")
        _parse_json();
    else
        _load_form_data();
}
